package cn.afactory.tygz.ui.base.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.lidroid.xutils.exception.DbException;

import java.io.IOException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import cn.afactory.tygz.TianYaGongZaiApplication;
import cn.afactory.tygz.cache.LocalJsonCache;
import cn.afactory.tygz.db.DBManager;
import cn.afactory.tygz.ui.user.LoginActivity;
import cn.afactory.tygz.ui.user.UserInfoCollectionActivity;

public class LocalUtils {
	private static final boolean D = true;
	private static final String DEFAULT_TAG = "Harwkin";
	public static void printLog(String tag,String content){
		if(content == null){
			return ;
		}
		if(D){
			Log.i(tag, content);
		}
	}
	
	public static void printLog(String content){
		if(content == null){
			return ;
		}
		if(D){
			Log.i(DEFAULT_TAG, content);
		}
	}
	
	public static String getMobilePhoneNumber(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getLine1Number();
	}

	public static String getIMSI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getSubscriberId();
	}

	public static String getIMEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	public static String getSimOperatorName(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getSimOperatorName();
	}
	
	public static void showToast(Context context,int msgResId){
		if(msgResId == -1){
			return ;
		}
		Toast.makeText(context, msgResId, Toast.LENGTH_SHORT).show();
	}
	
	public static void showToast(Context context,String msg){
		if(msg == null){
			return ;
		}
		if(context == null){
			return ;
		}
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}
	//获取版本号(内部识别号)
	public static int getVersionCode(Context context)
	{
		try {
			PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return 0;
		}
	}
	//获取版本号
	public static String getVersion(Context context)
	{
		try {
			PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "1.0.0.0";
		}
	}
	/**
	 * 判断sdcard是否存在
	 * @return
	 */
	public static boolean isSDCardMounted(){
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	/**
	 * 获取渠道号
	 * @param context
	 * @return
	 */
	public static String getChannel(Context context) {
		ApplicationInfo appinfo = context.getApplicationInfo();
		String sourceDir = appinfo.sourceDir;
		String ret = "";
		ZipFile zipfile = null;
		try {
			zipfile = new ZipFile(sourceDir);
			Enumeration<?> entries = zipfile.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = ((ZipEntry) entries.nextElement());
				String entryName = entry.getName();
				if (entryName.startsWith("META-INF/channel")) {
					ret = entryName;
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (zipfile != null) {
				try {
					zipfile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		String[] split = ret.split("_");
		if (split != null && split.length >= 2) {
			return ret.substring(split[0].length() + 1);
		} else {
			return "SJGW";
		}
	}

	public static int getAppVersionCode(Context context) {
		int version = 0;
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			version = info.versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
			version = 1;
		}
		return version;
	}

	/**
	 * 获取版本号
	 * @param context
	 * @return
     */
	public static String getVersionName(Context context) {
		String version = "";
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			version = "V" + info.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return version;
	}

	//是否为合法的手机号码
	public static boolean isPhoneNumber(String text) {
		if (text == null || text.length() == 0 || !text.matches("\\d{11}")) {
			return false;
		}
		return true;
	}
	//是否为合法的手机号码
	public static boolean isMobileNO(String mobiles) {
		if(!isPhoneNumber(mobiles)){
			return false;
		}
//		Pattern p = Pattern
//				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
//		Matcher m = p.matcher(mobiles);
		Pattern p = Pattern
				.compile("^((1[0-9]))\\d{9}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 跳转到登录页面
	 */
	public static void JumpToLogin(Activity context){
		clearLocalCache(context);
		DBManager.getInstance(context).release();
		((TianYaGongZaiApplication) context.getApplication()).exitAllActivity();

		Intent loginIntent = new Intent(context, LoginActivity.class);
		context.startActivity(loginIntent);
	}

	public static void clearLocalCache(Activity context){
		SPUtils.clearLogStatus(context);

		//清除json的缓存
		new LocalJsonCache(context).removeAll();
	}

	/**
	 * 发送广播
	 * @param context
	 * @param action
	 */
	public synchronized static void sendBroadcast(Context context,String action){
		context.sendBroadcast(new Intent(action));
	}

	/**
	 * 判断是否为主进程
	 * @param ctx
	 * @return
	 */
	public static boolean isMainProcess(Context ctx) {
		boolean isMainProcess = false;

		final int pid = android.os.Process.myPid();
		ActivityManager am = (ActivityManager) (ctx
				.getSystemService(Context.ACTIVITY_SERVICE));
		for (ActivityManager.RunningAppProcessInfo appProcess : am
				.getRunningAppProcesses()) {
			if (appProcess.pid == pid) {
				isMainProcess = appProcess.processName.equalsIgnoreCase(ctx.getPackageName());
				break;
			}
		}

		return isMainProcess;
	}
	//打电话
	public static void call(Context context,String phoneNum){
//		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNum));
//		context.startActivity(intent);
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	/**
	 * @return true快速点击，FALSE 非快速点击
	 */
	private static long lastClickTime = System.currentTimeMillis();
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeDuration = time - lastClickTime;

		if ( 0 < timeDuration && timeDuration < 500) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
}
